<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>流式聊天界面</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/marked@4.2.12/marked.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/lib/highlight.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/styles/github-dark.min.css">
  
  <!-- 配置Tailwind -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#64748B',
            accent: '#10B981',
            neutral: '#F8FAFC',
            'neutral-dark': '#1E293B'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
            mono: ['Consolas', 'Monaco', 'monospace']
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .scrollbar-hide {
        -ms-overflow-style: none;
        scrollbar-width: none;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .message-appear {
        animation: fadeIn 0.3s ease-in-out;
      }
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }
      .tab-active {
        @layer border-b-2 border-primary text-primary font-medium;
      }
      .tab-enter {
        animation: tabEnter 0.3s ease-out;
      }
      @keyframes tabEnter {
        from { opacity: 0; transform: translateX(-10px); }
        to { opacity: 1; transform: translateX(0); }
      }
      .tab-leave {
        animation: tabLeave 0.2s ease-in;
      }
      @keyframes tabLeave {
        from { opacity: 1; transform: translateX(0); }
        to { opacity: 0; transform: translateX(10px); }
      }
    }
  </style>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen flex flex-col">
  <!-- 顶部导航 -->
  <header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-4 flex justify-between items-center">
      <h1 class="text-2xl font-bold text-primary flex items-center">
        <i class="fa-solid fa-comments mr-2"></i>流式聊天界面
      </h1>
      <div class="flex space-x-2">
        <button id="new-conversation-btn" class="bg-accent hover:bg-accent/90 text-white px-4 py-2 rounded-full transition-all duration-300 flex items-center">
          <i class="fa-solid fa-refresh mr-2"></i>新会话
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-grow container mx-auto px-4 py-6 flex flex-col">
    <!-- Tab 控件 -->
    <div class="mb-4 border-b border-gray-200 flex flex-wrap items-center">
      <div id="tabs-container" class="flex space-x-1 overflow-x-auto pb-1 scrollbar-hide"></div>
      <div class="ml-2 flex space-x-2">
        <button id="add-tab-btn" class="bg-primary/10 hover:bg-primary/20 text-primary px-3 py-1 rounded-full text-sm transition-all duration-300 flex items-center">
          <i class="fa-solid fa-plus mr-1"></i>添加标签
        </button>
        <div class="relative">
          <button id="settings-menu-btn" class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-1 rounded-full text-sm transition-all duration-300 flex items-center">
            <i class="fa-solid fa-cog mr-1"></i>设置
          </button>
          <div id="settings-dropdown" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 z-10 hidden">
            <button id="save-config-btn" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              <i class="fa-solid fa-save mr-2"></i>保存设置
            </button>
            <button id="export-config-btn" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              <i class="fa-solid fa-download mr-2"></i>导出配置
            </button>
            <button id="import-config-btn" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
              <i class="fa-solid fa-upload mr-2"></i>导入配置
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- API配置区域将动态生成 -->
    <div id="api-configs-container"></div>

    <!-- 会话ID显示 -->
    <div id="conversation-id-container" class="bg-blue-50 border border-blue-100 rounded-xl p-4 mb-6 hidden transition-all duration-300">
      <h2 class="text-lg font-semibold mb-2 flex items-center">
        <i class="fa-solid fa-hashtag mr-2 text-primary"></i>当前会话 ID
      </h2>
      <p id="conversation-id" class="font-mono text-gray-700 bg-white/70 rounded-lg p-2 overflow-x-auto scrollbar-hide"></p>
    </div>

    <!-- 消息区域 -->
    <div class="flex-grow bg-white rounded-xl shadow-sm overflow-hidden flex flex-col mb-6">
      <div class="border-b border-gray-100 px-4 py-3 flex justify-between items-center">
        <h2 class="text-lg font-semibold flex items-center">
          <i class="fa-solid fa-comments mr-2 text-primary"></i>消息对话
        </h2>
        <span id="typing-indicator" class="text-sm text-gray-500 hidden">
          <i class="fa-solid fa-circle-notch fa-spin mr-1"></i>正在生成回复...
        </span>
      </div>
      <div id="messages-container" class="flex-grow p-4 overflow-y-auto max-h-[calc(100vh-350px)] scrollbar-hide space-y-4">
        <!-- 消息将动态添加到这里 -->
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="bg-white rounded-xl shadow-sm p-4 mb-6">
      <div class="mb-3">
        <label for="user-message" class="block text-sm font-medium text-gray-700 mb-1">您的问题</label>
        <div class="relative">
          <textarea 
            id="user-message" 
            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300 resize-none min-h-[100px]"
            placeholder="请输入您的问题..."
          ></textarea>
          <div class="absolute bottom-3 right-3 text-xs text-gray-400">
            <span id="char-count">0</span>/2000
          </div>
        </div>
      </div>
      <div class="flex justify-between items-center">
        <div class="text-sm text-gray-500">
          <i class="fa-solid fa-info-circle mr-1"></i>支持Markdown语法和代码块
        </div>
        <button id="send-message-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-full transition-all duration-300 flex items-center disabled:opacity-50 disabled:cursor-not-allowed">
          <span>发送消息</span>
          <i class="fa-solid fa-paper-plane ml-2"></i>
        </button>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-100 py-4">
    <div class="container mx-auto px-4 text-center text-sm text-gray-500">
      <p>© 2025 流式聊天界面 | 使用 Tailwind CSS 和 Font Awesome 构建</p>
    </div>
  </footer>

  <!-- 测试连接结果模态框 -->
  <div id="connection-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
      <div class="text-center mb-4">
        <div id="connection-status-icon" class="inline-flex items-center justify-center w-16 h-16 rounded-full mb-4">
          <i class="fa-solid fa-circle-check text-2xl"></i>
        </div>
        <h3 class="text-xl font-bold" id="connection-status-text">连接成功</h3>
      </div>
      <p id="connection-message" class="text-gray-600 mb-6 text-center">API 连接测试成功！</p>
      <div class="text-center">
        <button id="close-modal-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-full transition-all duration-300">
          关闭
        </button>
      </div>
    </div>
  </div>

  <!-- 重命名标签页模态框 -->
  <div id="rename-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="rename-modal-content">
      <h3 class="text-xl font-bold mb-4">重命名标签页</h3>
      <div class="mb-4">
        <input type="text" id="new-tab-name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="输入新的标签名">
      </div>
      <div class="flex justify-end space-x-3">
        <button id="cancel-rename-btn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-full transition-all duration-300">
          取消
        </button>
        <button id="confirm-rename-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-full transition-all duration-300">
          确认
        </button>
      </div>
    </div>
  </div>

  <!-- 导入配置模态框 -->
  <div id="import-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="import-modal-content">
      <h3 class="text-xl font-bold mb-4">导入配置</h3>
      <div class="mb-4">
        <p class="text-gray-600 mb-2">选择一个配置文件 (*.json) 导入：</p>
        <input type="file" id="config-file-input" accept=".json" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-primary/10 file:text-primary hover:file:bg-primary/20">
      </div>
      <div class="flex justify-end space-x-3">
        <button id="cancel-import-btn" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-full transition-all duration-300">
          取消
        </button>
        <button id="confirm-import-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-full transition-all duration-300" disabled>
          导入
        </button>
      </div>
    </div>
  </div>

  <!-- 操作结果提示框 -->
  <div id="toast" class="fixed bottom-4 right-4 bg-gray-800 text-white px-4 py-2 rounded-lg shadow-lg transform transition-all duration-300 translate-y-16 opacity-0 z-50">
    <div class="flex items-center">
      <i id="toast-icon" class="fa-solid fa-check-circle mr-2"></i>
      <span id="toast-message"></span>
    </div>
  </div>

  <script>
    // 初始化Marked配置
    marked.setOptions({
      highlight: function(code, lang) {
        if (lang && hljs.getLanguage(lang)) {
          return hljs.highlight(code, { language: lang }).value;
        }
        return hljs.highlightAuto(code).value;
      },
      breaks: true,
      gfm: true
    });

    // DOM元素
    const elements = {
      userMessage: document.getElementById('user-message'),
      sendMessageBtn: document.getElementById('send-message-btn'),
      messagesContainer: document.getElementById('messages-container'),
      conversationIdContainer: document.getElementById('conversation-id-container'),
      conversationId: document.getElementById('conversation-id'),
      newConversationBtn: document.getElementById('new-conversation-btn'),
      charCount: document.getElementById('char-count'),
      typingIndicator: document.getElementById('typing-indicator'),
      connectionModal: document.getElementById('connection-modal'),
      modalContent: document.getElementById('modal-content'),
      connectionStatusIcon: document.getElementById('connection-status-icon'),
      connectionStatusText: document.getElementById('connection-status-text'),
      connectionMessage: document.getElementById('connection-message'),
      closeModalBtn: document.getElementById('close-modal-btn'),
      tabsContainer: document.getElementById('tabs-container'),
      addTabBtn: document.getElementById('add-tab-btn'),
      apiConfigsContainer: document.getElementById('api-configs-container'),
      renameModal: document.getElementById('rename-modal'),
      renameModalContent: document.getElementById('rename-modal-content'),
      newTabName: document.getElementById('new-tab-name'),
      cancelRenameBtn: document.getElementById('cancel-rename-btn'),
      confirmRenameBtn: document.getElementById('confirm-rename-btn'),
      settingsMenuBtn: document.getElementById('settings-menu-btn'),
      settingsDropdown: document.getElementById('settings-dropdown'),
      saveConfigBtn: document.getElementById('save-config-btn'),
      exportConfigBtn: document.getElementById('export-config-btn'),
      importConfigBtn: document.getElementById('import-config-btn'),
      importModal: document.getElementById('import-modal'),
      importModalContent: document.getElementById('import-modal-content'),
      configFileInput: document.getElementById('config-file-input'),
      cancelImportBtn: document.getElementById('cancel-import-btn'),
      confirmImportBtn: document.getElementById('confirm-import-btn'),
      toast: document.getElementById('toast'),
      toastIcon: document.getElementById('toast-icon'),
      toastMessage: document.getElementById('toast-message')
    };

    // 状态管理
    let conversationId = null;
    let isStreaming = false;
    let controller = null;
    let activeTabId = 'tab-1';
    let currentTabIdForRename = null;
    let nextTabId = 2; // 从2开始，因为初始有一个tab-1

    // 标签页数据
    let tabsData = [
      {
        id: 'tab-1',
        name: '设置 1',
        apiUrl: 'http://127.0.0.1:8089/api/chat-messages',
        headers: [],
        method: 'POST' // 默认请求方式为POST
      }
    ];

    // 初始化
    function init() {
      loadSavedConfigs();
      initTabs();
      initSettingsMenu();
      initImportModal();
      
      // 添加重命名模态框按钮事件监听
      elements.cancelRenameBtn.addEventListener('click', closeRenameModal);
      elements.confirmRenameBtn.addEventListener('click', confirmRename);
      
      // 添加添加标签按钮事件监听
      elements.addTabBtn.addEventListener('click', () => addTab());
      
      addSystemMessage('欢迎使用流式聊天界面！请输入您的问题开始对话。');
    }

    // 初始化标签页
    function initTabs() {
      renderTabs();
      renderApiConfigs();
    }

    // 渲染标签页
    function renderTabs() {
      elements.tabsContainer.innerHTML = '';
      
      tabsData.forEach(tab => {
        const tabElement = document.createElement('div');
        tabElement.className = `flex items-center ${tab.id === activeTabId ? 'tab-active' : 'text-gray-500 hover:text-primary'}`;
        tabElement.setAttribute('data-tab', tab.id);
        tabElement.innerHTML = `
          <button class="py-2 px-3 focus:outline-none">${tab.name}</button>
          <button class="ml-1 text-gray-400 hover:text-red-500 focus:outline-none rename-tab-btn" title="重命名">
            <i class="fa-solid fa-pencil"></i>
          </button>
          <button class="ml-1 text-gray-400 hover:text-red-500 focus:outline-none delete-tab-btn" title="删除">
            <i class="fa-solid fa-times"></i>
          </button>
        `;
        elements.tabsContainer.appendChild(tabElement);
        
        // 添加标签页点击事件
        tabElement.querySelector('button:first-child').addEventListener('click', () => {
          switchTab(tab.id);
        });
        
        // 添加重命名按钮事件
        tabElement.querySelector('.rename-tab-btn').addEventListener('click', (e) => {
          e.stopPropagation();
          openRenameModal(tab.id);
        });
        
        // 添加删除按钮事件
        tabElement.querySelector('.delete-tab-btn').addEventListener('click', (e) => {
          e.stopPropagation();
          deleteTab(tab.id);
        });
      });
    }

    // 渲染API配置区域
    function renderApiConfigs() {
      elements.apiConfigsContainer.innerHTML = '';
      
      tabsData.forEach(tab => {
        const configElement = document.createElement('div');
        configElement.id = tab.id;
        configElement.className = `bg-white rounded-xl shadow-sm p-4 mb-6 transition-all duration-300 hover:shadow-md ${tab.id === activeTabId ? '' : 'hidden'}`;
        configElement.innerHTML = `
          <h2 class="text-lg font-semibold mb-3 flex items-center">
            <i class="fa-solid fa-cog mr-2 text-primary"></i>${tab.name} API 配置
          </h2>
          <div class="flex flex-col md:flex-row gap-4">
            <div class="flex-grow">
              <label for="api-url-${tab.id}" class="block text-sm font-medium text-gray-700 mb-1">API URL</label>
              <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                  <i class="fa-solid fa-link"></i>
                </span>
                <input 
                  type="text" 
                  id="api-url-${tab.id}" 
                  class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300"
                  value="${tab.apiUrl}"
                >
              </div>
            </div>
            <div class="flex items-end">
              <select id="method-select-${tab.id}" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary">
                <option value="POST" ${tab.method === 'POST' ? 'selected' : ''}>POST</option>
                <option value="GET" ${tab.method === 'GET' ? 'selected' : ''}>GET</option>
                <option value="PUT" ${tab.method === 'PUT' ? 'selected' : ''}>PUT</option>
              </select>
              <button id="test-connection-btn-${tab.id}" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-full transition-all duration-300 flex items-center ml-2">
                <i class="fa-solid fa-plug mr-2"></i>测试连接
              </button>
            </div>
          </div>
          <div class="mt-4">
            <h2 class="text-lg font-semibold mb-3 flex items-center">
              <i class="fa-solid fa-tags mr-2 text-primary"></i>请求头配置
            </h2>
            <div id="headers-container-${tab.id}" class="flex flex-col gap-2">
              ${tab.headers.map((header, index) => `
                <div class="flex gap-2">
                  <input type="text" placeholder="Header Key" value="${header.key}"
                    class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
                  <input type="text" placeholder="Header Value" value="${header.value}"
                    class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
                  <button class="ml-2 text-red-500 hover:text-red-700 focus:outline-none delete-header-btn" title="删除">
                    <i class="fa-solid fa-trash"></i>
                  </button>
                </div>
              `).join('')}
              <div class="flex gap-2">
                <input type="text" placeholder="Header Key" 
                  class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
                <input type="text" placeholder="Header Value" 
                  class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
              </div>
              <button id="add-header-btn-${tab.id}" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-full transition-all duration-300 flex items-center self-start">
                <i class="fa-solid fa-plus mr-2"></i>添加头
              </button>
            </div>
          </div>
        `;
        elements.apiConfigsContainer.appendChild(configElement);
        
        // 添加测试连接按钮事件
        const testBtn = document.getElementById(`test-connection-btn-${tab.id}`);
        testBtn.addEventListener('click', () => testConnection(tab.id));
        
        // 添加添加请求头按钮事件
        const addHeaderBtn = document.getElementById(`add-header-btn-${tab.id}`);
        addHeaderBtn.addEventListener('click', () => addHeader(tab.id));
        
        // 添加删除请求头按钮事件
        const deleteHeaderBtns = configElement.querySelectorAll('.delete-header-btn');
        deleteHeaderBtns.forEach(btn => {
          btn.addEventListener('click', (e) => {
            e.preventDefault();
            const headerRow = btn.closest('div');
            headerRow.remove();
          });
        });

        // 添加请求方式选择事件
        const methodSelect = document.getElementById(`method-select-${tab.id}`);
        methodSelect.addEventListener('change', () => {
          tab.method = methodSelect.value;
          saveConfigs();
        });
      });
    }

    // 切换标签页
    function switchTab(tabId) {
      if (activeTabId === tabId) return;
      
      // 更新活动标签页
      activeTabId = tabId;
      
      // 更新标签页样式
      document.querySelectorAll('[data-tab]').forEach(tab => {
        if (tab.getAttribute('data-tab') === tabId) {
          tab.classList.add('tab-active');
          tab.classList.remove('text-gray-500', 'hover:text-primary');
        } else {
          tab.classList.remove('tab-active');
          tab.classList.add('text-gray-500', 'hover:text-primary');
        }
      });
      
      // 更新API配置区域可见性
      document.querySelectorAll('[id^="tab-"]').forEach(tab => {
        if (tab.id === tabId) {
          tab.classList.remove('hidden');
        } else {
          tab.classList.add('hidden');
        }
      });
    }

    // 添加新标签页
    function addTab(name = `设置 ${nextTabId}`) {
      const tabId = `tab-${nextTabId}`;
      nextTabId++;
      
      tabsData.push({
        id: tabId,
        name: name,
        apiUrl: 'http://127.0.0.1:8089/api/chat-messages',
        headers: [],
        method: 'POST' // 默认请求方式为POST
      });
      
      renderTabs();
      renderApiConfigs();
      switchTab(tabId);
      
      // 高亮显示新标签页
      const newTab = document.querySelector(`[data-tab="${tabId}"]`);
      newTab.classList.add('animate-pulse');
      setTimeout(() => {
        newTab.classList.remove('animate-pulse');
      }, 1000);
      
      // 保存配置
      saveConfigs();
    }

    // 删除标签页
    function deleteTab(tabId) {
      // 至少保留一个标签页
      if (tabsData.length <= 1) {
        showToast('至少保留一个标签页', 'error');
        return;
      }
      
      // 如果删除的是当前活动标签页，切换到前一个标签页
      if (tabId === activeTabId) {
        const currentIndex = tabsData.findIndex(tab => tab.id === tabId);
        const newActiveTabId = currentIndex > 0 ? tabsData[currentIndex - 1].id : tabsData[currentIndex + 1].id;
        switchTab(newActiveTabId);
      }
      
      // 从DOM中移除标签页
      const tabElement = document.querySelector(`[data-tab="${tabId}"]`);
      tabElement.classList.add('tab-leave');
      setTimeout(() => {
        // 从数据中移除标签页
        const index = tabsData.findIndex(tab => tab.id === tabId);
        if (index !== -1) {
          tabsData.splice(index, 1);
        }
        
        // 重新渲染
        renderTabs();
        renderApiConfigs();
        
        // 保存配置
        saveConfigs();
      }, 200);
    }

    // 打开重命名模态框
    function openRenameModal(tabId) {
      const tab = tabsData.find(t => t.id === tabId);
      if (!tab) return;
      
      currentTabIdForRename = tabId;
      elements.newTabName.value = tab.name;
      
      // 显示模态框
      elements.renameModal.classList.remove('hidden');
      setTimeout(() => {
        elements.renameModalContent.classList.remove('scale-95', 'opacity-0');
        elements.renameModalContent.classList.add('scale-100', 'opacity-100');
      }, 10);
      
      // 自动聚焦输入框
      elements.newTabName.focus();
    }

    // 关闭重命名模态框
    function closeRenameModal() {
      elements.renameModalContent.classList.remove('scale-100', 'opacity-100');
      elements.renameModalContent.classList.add('scale-95', 'opacity-0');
      setTimeout(() => {
        elements.renameModal.classList.add('hidden');
        currentTabIdForRename = null;
      }, 300);
    }

    // 确认重命名
    function confirmRename() {
      const newName = elements.newTabName.value.trim();
      if (!newName || !currentTabIdForRename) {
        closeRenameModal();
        return;
      }
      
      // 更新标签页名称
      const tabIndex = tabsData.findIndex(t => t.id === currentTabIdForRename);
      if (tabIndex !== -1) {
        tabsData[tabIndex].name = newName;
      }
      
      // 重新渲染
      renderTabs();
      closeRenameModal();
      
      // 保存配置
      saveConfigs();
    }

    // 添加请求头
    function addHeader(tabId) {
      const container = document.getElementById(`headers-container-${tabId}`);
      const addBtn = document.getElementById(`add-header-btn-${tabId}`);
      
      const headerInput = document.createElement('div');
      headerInput.className = 'flex gap-2';
      headerInput.innerHTML = `
        <input type="text" placeholder="Header Key" 
          class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
        <input type="text" placeholder="Header Value" 
          class="w-1/2 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300">
        <button class="ml-2 text-red-500 hover:text-red-700 focus:outline-none delete-header-btn" title="删除">
          <i class="fa-solid fa-trash"></i>
        </button>
      `;
      
      container.insertBefore(headerInput, addBtn);
      
      // 添加删除按钮事件
      const deleteBtn = headerInput.querySelector('.delete-header-btn');
      deleteBtn.addEventListener('click', (e) => {
        e.preventDefault();
        headerInput.remove();
      });
    }

    // 获取当前活动标签页的API URL
    function getActiveApiUrl() {
      const tab = tabsData.find(t => t.id === activeTabId);
      return tab ? tab.apiUrl : '';
    }

    // 获取当前活动标签页的请求头
    function getActiveHeaders() {
      const headers = {};
      const container = document.getElementById(`headers-container-${activeTabId}`);
      if (!container) return headers;
      
      const inputs = container.querySelectorAll('input');
      
      for (let i = 0; i < inputs.length; i += 2) {
        const key = inputs[i].value.trim();
        const value = inputs[i + 1].value.trim();
        if (key && value) {
          headers[key] = value;
        }
      }
      
      return headers;
    }

    // 获取当前活动标签页的请求方式
    function getActiveMethod() {
      const tab = tabsData.find(t => t.id === activeTabId);
      return tab ? tab.method : 'POST';
    }

    // 保存当前配置到localStorage
    function saveConfigs() {
      // 更新每个标签页的数据
      tabsData.forEach(tab => {
        const urlInput = document.getElementById(`api-url-${tab.id}`);
        if (urlInput) {
          tab.apiUrl = urlInput.value;
        }
        
        const headers = [];
        const container = document.getElementById(`headers-container-${tab.id}`);
        if (container) {
          const inputs = container.querySelectorAll('input');
          
          for (let i = 0; i < inputs.length; i += 2) {
            const key = inputs[i].value.trim();
            const value = inputs[i + 1].value.trim();
            if (key && value) {
              headers.push({ key, value });
            }
          }
        }
        
        tab.headers = headers;

        const methodSelect = document.getElementById(`method-select-${tab.id}`);
        if (methodSelect) {
          tab.method = methodSelect.value;
        }
      });
      
      // 保存到localStorage
      localStorage.setItem('chat_configs', JSON.stringify({
        tabsData,
        activeTabId,
        nextTabId
      }));
      
      showToast('配置已保存', 'success');
    }

    // 从localStorage加载配置
    function loadSavedConfigs() {
      const savedConfigs = localStorage.getItem('chat_configs');
      if (savedConfigs) {
        try {
          const parsed = JSON.parse(savedConfigs);
          if (parsed.tabsData && Array.isArray(parsed.tabsData) && parsed.tabsData.length > 0) {
            tabsData = parsed.tabsData;
            activeTabId = parsed.activeTabId || 'tab-1';
            nextTabId = parsed.nextTabId || 2;
          }
        } catch (error) {
          console.error('加载保存的配置失败:', error);
        }
      }
    }

    // 导出配置
    function exportConfigs() {
      // 保存当前配置
      saveConfigs();
      
      // 创建JSON字符串
      const configJson = JSON.stringify({
        tabsData,
        activeTabId,
        nextTabId
      }, null, 2);
      
      // 创建Blob对象
      const blob = new Blob([configJson], { type: 'application/json' });
      
      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'chat_configs.json';
      
      // 触发下载
      document.body.appendChild(a);
      a.click();
      
      // 清理
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      showToast('配置已导出', 'success');
    }

    // 导入配置
    function importConfigs(configData) {
      try {
        const parsed = JSON.parse(configData);
        
        if (!parsed.tabsData || !Array.isArray(parsed.tabsData) || parsed.tabsData.length === 0) {
          throw new Error('无效的配置文件');
        }
        
        // 更新配置
        tabsData = parsed.tabsData;
        activeTabId = parsed.activeTabId || 'tab-1';
        nextTabId = parsed.nextTabId || 2;
        
        // 重新渲染
        initTabs();
        
        // 保存配置
        saveConfigs();
        
        showToast('配置已导入', 'success');
      } catch (error) {
        console.error('导入配置失败:', error);
        showToast(`导入失败: ${error.message}`, 'error');
      }
    }

    // 初始化设置菜单
    function initSettingsMenu() {
      // 设置菜单点击事件
      elements.settingsMenuBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        elements.settingsDropdown.classList.toggle('hidden');
      });
      
      // 点击页面其他地方关闭菜单
      document.addEventListener('click', () => {
        elements.settingsDropdown.classList.add('hidden');
      });
      
      // 保存配置按钮事件
      elements.saveConfigBtn.addEventListener('click', () => {
        saveConfigs();
        elements.settingsDropdown.classList.add('hidden');
      });
      
      // 导出配置按钮事件
      elements.exportConfigBtn.addEventListener('click', () => {
        exportConfigs();
        elements.settingsDropdown.classList.add('hidden');
      });
      
      // 导入配置按钮事件
      elements.importConfigBtn.addEventListener('click', () => {
        elements.importModal.classList.remove('hidden');
        elements.settingsDropdown.classList.add('hidden');
        setTimeout(() => {
          elements.importModalContent.classList.remove('scale-95', 'opacity-0');
          elements.importModalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
      });
    }

    // 初始化导入模态框
    function initImportModal() {
      // 文件选择事件
      elements.configFileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        elements.confirmImportBtn.disabled = !file;
      });
      
      // 取消导入
      elements.cancelImportBtn.addEventListener('click', () => {
        closeImportModal();
      });
      
      // 确认导入
      elements.confirmImportBtn.addEventListener('click', () => {
        const file = elements.configFileInput.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = (e) => {
          importConfigs(e.target.result);
          closeImportModal();
        };
        reader.readAsText(file);
      });
      
      // 点击模态框背景关闭
      elements.importModal.addEventListener('click', (e) => {
        if (e.target === elements.importModal) {
          closeImportModal();
        }
      });
    }

    // 关闭导入模态框
    function closeImportModal() {
      elements.importModalContent.classList.remove('scale-100', 'opacity-100');
      elements.importModalContent.classList.add('scale-95', 'opacity-0');
      setTimeout(() => {
        elements.importModal.classList.add('hidden');
        elements.configFileInput.value = '';
        elements.confirmImportBtn.disabled = true;
      }, 300);
    }

    // 显示提示框
    function showToast(message, type = 'success') {
      elements.toastMessage.textContent = message;
      
      if (type === 'success') {
        elements.toastIcon.className = 'fa-solid fa-check-circle mr-2';
        elements.toast.classList.remove('bg-red-600');
        elements.toast.classList.add('bg-green-600');
      } else {
        elements.toastIcon.className = 'fa-solid fa-exclamation-circle mr-2';
        elements.toast.classList.remove('bg-green-600');
        elements.toast.classList.add('bg-red-600');
      }
      
      elements.toast.classList.remove('translate-y-16', 'opacity-0');
      elements.toast.classList.add('translate-y-0', 'opacity-100');
      
      setTimeout(() => {
        elements.toast.classList.remove('translate-y-0', 'opacity-100');
        elements.toast.classList.add('translate-y-16', 'opacity-0');
      }, 3000);
    }

    // 更新字符计数
    elements.userMessage.addEventListener('input', () => {
      const length = elements.userMessage.value.length;
      elements.charCount.textContent = length;
      
      if (length > 2000) {
        elements.charCount.classList.add('text-red-500');
        elements.sendMessageBtn.disabled = true;
      } else {
        elements.charCount.classList.remove('text-red-500');
        elements.sendMessageBtn.disabled = elements.userMessage.value.trim() === '' || isStreaming;
      }
    });

    // 发送消息
    elements.sendMessageBtn.addEventListener('click', sendMessage);
    
    // 支持Enter发送消息，Shift+Enter换行
    elements.userMessage.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        if (!elements.sendMessageBtn.disabled) {
          sendMessage();
        }
      }
    });

    // 开始新会话
    elements.newConversationBtn.addEventListener('click', () => {
      if (isStreaming) {
        controller.abort();
        isStreaming = false;
        elements.typingIndicator.classList.add('hidden');
      }
      
      conversationId = null;
      elements.conversationIdContainer.classList.add('hidden');
      elements.messagesContainer.innerHTML = '';
      
      // 添加欢迎消息
      addSystemMessage('欢迎使用流式聊天界面！请输入您的问题开始对话。');
    });

    // 测试连接
    elements.closeModalBtn.addEventListener('click', () => {
      closeModal();
    });

    // 测试API连接
    async function testConnection(tabId) {
      const tab = tabsData.find(t => t.id === tabId);
      if (!tab) return;
      
      const url = document.getElementById(`api-url-${tabId}`).value.trim();
      
      if (!url) {
        showConnectionResult(false, '错误', '请输入API URL');
        return;
      }
      
      // 更新标签页数据中的URL
      tab.apiUrl = url;

      const method = getActiveMethod(); // 获取当前活动标签页的请求方式
      
      try {
        const response = await fetch(url, {
          method: method,
          headers: {
            ...getActiveHeaders(),
            'Accept': '*/*'
          }
        });

        if (response.ok) {
          showConnectionResult(true, '成功', 'API 连接测试成功！');
        } else {
          showConnectionResult(false, '失败', `API 连接测试失败：${response.status} ${response.statusText}`);
        }
      } catch (error) {
        showConnectionResult(false, '错误', `API 连接测试出错：${error.message}`);
      }
    }

    // 显示连接结果模态框
    function showConnectionResult(success, status, message) {
      elements.connectionStatusIcon.innerHTML = success ? '<i class="fa-solid fa-circle-check text-2xl text-green-500"></i>' : '<i class="fa-solid fa-circle-xmark text-2xl text-red-500"></i>';
      elements.connectionStatusText.textContent = status;
      elements.connectionMessage.textContent = message;

      elements.connectionModal.classList.remove('hidden');
      setTimeout(() => {
        elements.modalContent.classList.remove('scale-95', 'opacity-0');
        elements.modalContent.classList.add('scale-100', 'opacity-100');
      }, 10);
    }

    // 关闭连接结果模态框
    function closeModal() {
      elements.modalContent.classList.remove('scale-100', 'opacity-100');
      elements.modalContent.classList.add('scale-95', 'opacity-0');
      setTimeout(() => {
        elements.connectionModal.classList.add('hidden');
      }, 300);
    }

    // 添加系统消息
    function addSystemMessage(message) {
      const messageElement = document.createElement('div');
      messageElement.className = 'message-appear bg-gray-100 rounded-lg p-4 text-gray-700';
      messageElement.innerHTML = `<p>${message}</p>`;
      elements.messagesContainer.appendChild(messageElement);
      elements.messagesContainer.scrollTop = elements.messagesContainer.scrollHeight;
    }

    // 发送消息
    async function sendMessage() {
      const message = elements.userMessage.value.trim();
      if (!message || isStreaming) return;

      isStreaming = true;
      elements.sendMessageBtn.disabled = true;
      elements.typingIndicator.classList.remove('hidden');

      const url = getActiveApiUrl();
      const headers = getActiveHeaders();
      const method = getActiveMethod(); // 获取当前活动标签页的请求方式

      try {
        controller = new AbortController();
        const signal = controller.signal;

        const response = await fetch(url, {
          method: method,
          headers: {
            ...headers,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message: message,
            conversationId: conversationId
          }),
          signal: signal
        });

        if (!response.ok) {
          throw new Error(`请求失败：${response.status} ${response.statusText}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let result = '';

        const messageElement = document.createElement('div');
        messageElement.className = 'message-appear bg-blue-100 rounded-lg p-4 text-gray-700';
        elements.messagesContainer.appendChild(messageElement);

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          result += chunk;
          messageElement.innerHTML = marked.parse(result);

          elements.messagesContainer.scrollTop = elements.messagesContainer.scrollHeight;
        }

        // 更新会话ID
        const data = JSON.parse(result);
        if (data.conversationId) {
          conversationId = data.conversationId;
          elements.conversationId.textContent = conversationId;
          elements.conversationIdContainer.classList.remove('hidden');
        }
      } catch (error) {
        if (error.name === 'AbortError') {
          showToast('请求已取消', 'error');
        } else {
          showToast(`请求出错：${error.message}`, 'error');
        }
      } finally {
        isStreaming = false;
        elements.sendMessageBtn.disabled = false;
        elements.typingIndicator.classList.add('hidden');
        elements.userMessage.value = '';
        elements.charCount.textContent = '0';
      }
    }

    // 初始化
    init();
  </script>
</body>
</html>